package com.ease.common.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.IllegalFormatException;
import java.util.TimeZone;

import org.apache.commons.lang.StringUtils;

/**
 * 
 * @author nathanleewei
 * 
 */
public class DateToXsdDatetimeFormatter {

	private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

	public DateToXsdDatetimeFormatter() {
	}

	public DateToXsdDatetimeFormatter(TimeZone timeZone) {
		simpleDateFormat.setTimeZone(timeZone);
	}

	/**
	 * Parse a xml date string in the format produced by this class only. This method cannot parse all valid xml date
	 * string formats - so don't try to use it as part of a general xml parser
	 */
	public synchronized Date parse(String xmlDateTime) throws ParseException {
		if (StringUtils.isEmpty(xmlDateTime))
			return null;
		if (xmlDateTime.length() != 25) {
			throw new ParseException("Date not in expected xml datetime format", 0);
		}

		StringBuilder sb = new StringBuilder(xmlDateTime);
		sb.deleteCharAt(22);
		return simpleDateFormat.parse(sb.toString());
	}

	public synchronized String format(Date xmlDateTime) throws IllegalFormatException {
		if (null == xmlDateTime)
			return StringUtils.EMPTY;
		String s = simpleDateFormat.format(xmlDateTime);
		StringBuilder sb = new StringBuilder(s);
		sb.insert(22, ':');
		return sb.toString();
	}

	public synchronized void setTimeZone(String timezone) {
		simpleDateFormat.setTimeZone(TimeZone.getTimeZone(timezone));
	}
}
